﻿#include "local_socket.h"

local_socket::local_socket(QString name)
{
     this->connect_name=name;
     connect(this,SIGNAL(readyRead()),this,SLOT(receive()));
     connect(this,SIGNAL(disconnected()),this,SLOT(Reconnect()),Qt::QueuedConnection);
}

bool local_socket::localSocket_init()
{
    Reconnect();
    return true;
}

void local_socket::receive()
{
    receive_data+=read(bytesAvailable());

    if(receive_datasize!=0||receive_data.size()>=receive_datasize)
    {
    analyse_data();
    }
}

void local_socket::analyse_data()
{
    while(receive_data.size()>(int(sizeof(qint32)+sizeof(qint64))))
    {
        qint64 data_size;
        qint32 feature;
        QByteArray data;
        QDataStream dts(&receive_data,QIODevice::ReadWrite);
        dts>>feature>>data_size;
        if(feature==this->feature)
        {
            if(data_size<=receive_data.size())
            {
                dts.device()->seek(sizeof(qint32)+sizeof(qint64));
                dts>>data;
                /* if(data.size()<1000)
                   qDebug()<<data;
               else
                   qDebug()<<data.size();*/
                receive_data.remove(0,data_size);
                process_data(data);
            }
            else
            {
                break;
            }
        }
        else
        {
            qDebug()<<"特征值错误，断开socket";
            disconnectFromServer();
            break;
        }
    }
}


void local_socket::process_data(QByteArray data)
{
    QString id,type,information;
    //qDebug()<<data;
    QStringList result=json_analyse(data);
   // qDebug()<<result;
    id=result[0];
    type=result[1];
    information=result[2];
    emit reply_data(id,type,information);
}

QStringList local_socket::json_analyse(QByteArray data)
{
    QString id,type,message;
    QStringList result;
    QJsonParseError json_error;
    QJsonDocument parse_doucment = QJsonDocument::fromJson(data, &json_error);
    if(json_error.error == QJsonParseError::NoError)
    {
        if(parse_doucment.isObject())
        {
            QJsonObject obj = parse_doucment.object();
            if(obj.contains("id"))
            {
                QJsonValue id_value = obj.take("id");
                if(id_value.isString())
                {
                    id = id_value.toString();
                }
            }
            if(obj.contains("type"))
            {
                QJsonValue type_value = obj.take("type");
                if(type_value.isString())
                {
                    type = type_value.toString();
                }
            }
            if(obj.contains("data"))
            {
                QJsonValue data_value = obj.take("data");
                if(data_value.isString())
                {
                    message = data_value.toString();
                }
            }
            result<<id<<type<<message;
           // qDebug()<<"json解析结果为:"<<result;

        }
        else
        {
            qDebug()<<"json不是对象";
        }

    }
    else
    {
        qDebug()<<"json格式错误！";
    }
    return result;
}

QByteArray local_socket::json_pack(QString id, QString type, QString data)
{
    QJsonObject json;
    json.insert("id", id);
    json.insert("type", type);
    json.insert("data", data);
    QJsonDocument document;
    document.setObject(json);
    QByteArray byte_array = document.toJson(QJsonDocument::Compact);
    return byte_array;
}


void local_socket::Reconnect()
{
    bool isconnect=false;
    while(!isconnect)
    {
        abort(); //取消已有的连接
        connectToServer(this->connect_name);
        if (!waitForConnected(3000))
        {
            qDebug()<<"连接服务器失败!请检查ip,端口";
        }
        else
        {
            qDebug()<<"连接服务器成功";

        }
        if(state()==QAbstractSocket::ConnectedState)
        {
            isconnect=true;
        }
        QTime t;
        t.start();
        while(t.elapsed()<10000)
        QCoreApplication::processEvents();
    }
}


void local_socket::senddata(QByteArray data)
{
    if(this->state()==QLocalSocket::ConnectedState)
    {
    QByteArray senddata;
    QDataStream dts(&senddata,QIODevice::WriteOnly);
    dts<<(qint32)0<<(qint64)0<<data;
    dts.device()->seek(0);
    dts<<feature;
    dts.device()->seek(sizeof(qint32));
    dts<<(qint64)senddata.size();
    write(senddata);
    flush();
    waitForBytesWritten(3000);
    }
}

void local_socket::send_message(QString id, QString type, QString data)
{
    senddata(json_pack(id,type,data));
}
